package cn.taobaoke.restful.controller;

import cn.taobaoke.restful.domain.GlobalConfig;
import cn.taobaoke.restful.interceptor.Auth;
import cn.taobaoke.restful.service.GlobalConfigService;
import cn.taobaoke.restful.util.Constants;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yangzuo
 * @since 2017-03-27
 */
@RestController
@RequestMapping("/{domain}/{domainId}/api/configs")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class GlobalConfigController extends BaseController {

    @Auth(type = {Auth.AuthType.ADMIN, Auth.AuthType.AGENT})
    @PutMapping("")
    public Result storeConfig(@PathVariable Long domainId, @RequestBody Map<String, Object> data) {
        logger.debug("PUT /{}/api/configs", domainId);

        Map<String, Object> oldData = globalConfigService.queryConfig(domainId);
        if (data != null) {
            // AMIND_PID 不进行替换
            data.put(Constants.ADMIN_PID, oldData.get(Constants.ADMIN_PID));
            String template = (String) data.get("template");
            if (template == null || template.trim().isEmpty()) {
                data.put(Constants.SEND_PRODUCT_TEMPLATE, oldData.get(Constants.SEND_PRODUCT_TEMPLATE));
            } else {
                logger.info("template => {}", template);
            }
        }
        globalConfigService.storeConfig(data, domainId);
        return wrapObj(globalConfigService.queryConfig(domainId));
    }

    @Auth(type = {Auth.AuthType.ADMIN, Auth.AuthType.AGENT})
    @GetMapping("")
    public Result getConfig(@PathVariable Long domainId) {
        logger.debug("GET /{}/api/configs", domainId);

        return wrapObj(globalConfigService.queryConfig(domainId));
    }


    @GetMapping("/logo")
    public Result getLogoAndTitle(@PathVariable Long domainId) {
        GlobalConfig config = globalConfigService.getConfig(domainId);
        Map<String, Object> map = new HashMap<>();

        if (config != null && config.getLogoUrl() != null) {
            map.put("logoUrl", config.getLogoUrl());
        }
        if (config != null && config.getTitle() != null) {
            map.put("title", config.getTitle());
        }
        return wrapObj(map);
    }

    private final @NonNull GlobalConfigService globalConfigService;

    private static Logger logger = LogManager.getLogger(GlobalConfigController.class);
}
